package vn.com.epi.buffer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;

import javax.servlet.ServletContext;

import vn.com.epi.web.Application;

import com.google.common.collect.Lists;

public class LogBuffer {

	private Queue<String[]> buffer = Lists.newLinkedList();
	private int throughput = 0;
	private int lineCount = 0;
	private int max;

	public LogBuffer(int max) {
		this.max = max;
	}

	public void add(ServletContext servletContext, String... lines) throws IOException {
		synchronized (buffer) {
			buffer.add(lines);
			lineCount += lines.length;
			throughput += lines.length;
			if (lineCount >= max) {
				flush(servletContext);
			}
		}
	}
	
	public int getLineCount() {
		return lineCount;
	}
	
	public int getThroughput() {
		return throughput;
	}
	
	public void flush(ServletContext servletContext) throws IOException {
        if (buffer.isEmpty()) {
            return;
        }
        File dir = new File(servletContext.getInitParameter(Application.LOG_DIR_PARAM));
        File path = new File(dir, "cfratings.csv"); 
        FileOutputStream fo = new FileOutputStream(path, true);
        OutputStreamWriter osw = new OutputStreamWriter(fo, "utf-8");
        try {
            while (!buffer.isEmpty()) {
                String[] lines = buffer.poll();
                for (String line : lines) {
                    osw.write(line + "\n");
                }
            }
            lineCount = 0;
        } finally {
            osw.flush();
            fo.close();            
        }	
	}
	
	public List<String> toList() {
	    List<String> list = Lists.newArrayList();
        Iterator<String[]> it= buffer.iterator();
        while(it.hasNext())
        {
            String[] lines = (String[]) it.next();
            for (int i = 0; i < lines.length; i++) {
                list.add(lines[i]);
            }
        }
	    return list;
	}

}
